package com.jiuyin.dianjing.ui.activity.community;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.SectionQuickAdapter;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.entity.MySection;
import com.jiuyin.dianjing.model.UniversityClub;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.jiuyin.dianjing.view.GridSectionAverageGapItemDecoration;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_WORD;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_FIRST;

public class CollegeListActivity extends BaseActivity {
    public static final int REQUEST_APPLY = 75;
    @BindView(R.id.grid_colleges)
    RecyclerView mRecyclerView;
    @BindView(R.id.et_search)
    EditText mSearchView;
    SectionQuickAdapter adapter;
    ArrayList<MySection> mData = new ArrayList<>();
    private int mPageNum = PAGE_FIRST;
    private String status;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_college_list;
    }

    @Override
    protected void initData() {
        fetchData(true);
    }

    private void fetchData(boolean refresh) {
        if (refresh) {
            mPageNum = PAGE_FIRST;
        } else {
            mPageNum += 1;
        }

        HashMap<String, Object> data = new HashMap<>();
        data.put(KEY_TOKEN, HelperApplication.getToken());
        data.put(KEY_WORD, mSearchView.getText().toString());
        data.put(KEY_PAGE_NUM, mPageNum);
        JSONObject jsonObject = new JSONObject(data);
        ApiResultCallback requestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                List<UniversityClub> newData = new Gson().fromJson(data.get("universityClubList"), new TypeToken<List<UniversityClub>>() {
                }.getType());
                if (refresh) {
                    mData.clear();
                    mData.add(new MySection(true, "我的电竞社"));
                    UniversityClub club = new UniversityClub();
                    status = String.valueOf(data.get("status"));
                    if (status.equals("0")) {
                        club.name = "电竞社申请中";
                    } else if (status.equals("1")) {
                        if (data.has("universityClub")){
                            club = new Gson().fromJson(data.get("universityClub"),UniversityClub.class);
                        }
                    } else {
                        club.name = "申请高校电竞社";
                    }
                    MySection mine = new MySection(false, club);
                    List<MySection> exceptMine = new ArrayList<>();
                    for (UniversityClub newDatum : newData) {
                        if (newDatum.isJoin == 1) {
                            mine = new MySection(false, newDatum);//用我的电竞社替换"申请高校电竞社"
                        } else {
                            exceptMine.add(new MySection(false, newDatum));
                        }
                    }
                    mData.add(mine);
                    mData.add(new MySection(true, null));
                    mData.add(new MySection(true, "全部电竞社"));
                    mData.addAll(exceptMine);
                } else {
                    List<MySection> moreData = new ArrayList<>();
                    for (UniversityClub newDatum : newData) {
                        moreData.add(new MySection(false, newDatum));
                    }
                    mData.addAll(moreData);
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(String msg) {
                super.onError(msg);
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
            }
        };
        ServerApi.post(ApiEnum.GET_UNIVERSITY_CLUB_LIST, jsonObject, null, progress, d -> addDisposable(d), requestCallback);
    }

    @Override
    protected void initView() {
        setTitle("高校电竞社");
        mSearchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                fetchData(true);
            }
        });
        mSearchView.setOnEditorActionListener((v, actionId, event) -> {
            String content = v.getText().toString().trim();
            if (!TextUtils.isEmpty(content)) {
                fetchData(true);
            }
            IMEUtil.hideInputMethod(CollegeListActivity.this);
            return true;
        });
        mSearchView.setOnTouchListener((v, event) -> {
            Drawable drawable = mSearchView.getCompoundDrawables()[2];
            if (drawable == null) {
                return false;
            }
            if (event.getAction() != MotionEvent.ACTION_UP) {
                return false;

            }
            if (TextUtils.isEmpty(mSearchView.getText().toString())) {
                return false;
            }
            if (event.getX() > mSearchView.getWidth()
                    - mSearchView.getPaddingRight()
                    - drawable.getIntrinsicWidth()) {
                mSearchView.setText("");
            }
            return false;
        });
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        mRecyclerView.addItemDecoration(new GridSectionAverageGapItemDecoration(10, 10, 20, 15));
        adapter = new SectionQuickAdapter(this, R.layout.item_college, R.layout.item_section_head, mData) {

            @Override
            protected void convert(@NotNull BaseViewHolder helper, MySection item) {
                //设置item数据
                UniversityClub club = (UniversityClub) item.getObject();
                if (TextUtils.isEmpty(club.universityclub_id)) {
                    helper.setImageResource(R.id.iv_background, R.drawable.sqgxdjs);
                    helper.setText(R.id.tv_name, club.name);
                } else {
                    ImageView ivBackground = helper.itemView.findViewById(R.id.iv_background);
                    Glide.with(getContext())
                            .load(club.list_logo)
                            .override(ivBackground.getWidth(), ivBackground.getHeight())
                            .into(ivBackground);
                    helper.setText(R.id.tv_name, club.name);
                }
            }
        };
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                MySection mySection = mData.get(position);
                if (!mySection.isHeader()) {
                    UniversityClub club = (UniversityClub) mySection.getObject();
                    if (TextUtils.isEmpty(club.universityclub_id)) {
                        if (status.equals("0")){
                            ToastUtil.showShort("电竞社申请中");
                        }else {
                            Intent intent = new Intent(CollegeListActivity.this, CollegeApplyActivity.class);
                            startActivityForResult(intent, REQUEST_APPLY);
                        }
                    } else {
                        Intent intent = new Intent(CollegeListActivity.this, CollegeMainActivity.class);
                        intent.putExtra("UniversityClub", club);
                        startActivity(intent);
                    }
                }
            }
        });
        mRecyclerView.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_APPLY && resultCode == RESULT_OK) {
            initData();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
